﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Mime;
using EMPPLib;
using System.Threading;
using LDSP.BRL;

namespace BLL.Util
{
    public class SMSSender
    {
        public static void SendSMS(IList<SMSMessage> messages)
        {
            new SMSHandler().SendSMS(messages);
        }
    }

    public class SMSHandler
    {
        string host = "211.136.163.68";
        int port = 9981;
        string accountId = "0996340900010";//0996340900010
        string serviceId = "0";
        string password = "gpgp";//gpgp
        public EMPPLib.emptcl empp = new EMPPLib.emptclClass();

        #region
        public void SendSMS(IList<SMSMessage> messages)
        {
            //建立事件响应
            CreatePro(this.empp);

            //建立连接
            Connect();

            for (int i = 0; i < messages.Count; i++)
            {
                //初始化短消息
                EMPPLib.ShortMessage shortMsg = InitalMessage(messages[i]);

                if (empp != null && empp.connected == true)
                {
                    //发送短消息
                    SendMessage(shortMsg, i);
                }
                else
                {
                    //重连并发送短消息
                    ReconnectAndSendMessage(shortMsg, i);
                }
            }
        }

        private ShortMessage InitalMessage(SMSMessage message)
        {
            EMPPLib.ShortMessage shortMsg = new EMPPLib.ShortMessageClass();
            shortMsg.srcID = accountId;
            shortMsg.ServiceID = serviceId;
            shortMsg.needStatus = true;

            EMPPLib.Mobiles mobs = new EMPPLib.MobilesClass();
            mobs.Add(message.PhoneNumber);
            shortMsg.DestMobiles = mobs;
            shortMsg.content = message.Content;
            shortMsg.SendNow = true;
            empp.needStatus = true;

            LogUtil.toLog("原始的短信内容：" + message.Content);

            return shortMsg;
        }

        private void ReconnectAndSendMessage(ShortMessage shortMsg, int i)
        {
            LogUtil.toLog("连接已经关闭，即将重新连接。。。");
            Reconnect();
            Console.WriteLine("即将发送短信，第" + i + "条短信");
            Console.WriteLine("连接状况: " + empp.connected);

            LogUtil.toLog("\r\n");
            LogUtil.toLog("目前的连接状况：" + empp.connected);
            LogUtil.toLog("目前的shortmsgseqid是：" + shortMsg.SequenceID);
            LogUtil.toLog("目前的emppseqid是：" + empp.SequenceID);

            LogUtil.toLog("发送短信：" + shortMsg.content + "。。。");
            empp.submit(shortMsg);
            LogUtil.toLog("短信发送成功：" + shortMsg.content);

            Console.WriteLine("短信提交结束" + i);
            Console.WriteLine("end empp.SequenceID:" + empp.SequenceID);
            Console.WriteLine("");
            Thread.Sleep(2000);
        }

        private void SendMessage(ShortMessage shortMsg, int i)
        {
            Console.WriteLine("即将发送短信，第" + i + "条短信");
            Console.WriteLine("连接状况: " + empp.connected);

            LogUtil.toLog("\r\n");
            LogUtil.toLog("连接状况：" + empp.connected);
            LogUtil.toLog("短信的seqid是：" + shortMsg.SequenceID);
            LogUtil.toLog("the empp.sequceid:" + empp.SequenceID);
            LogUtil.toLog("发送短信：" + shortMsg.content + "。。。");
            empp.submit(shortMsg);

            LogUtil.toLog("短信已发送：" + shortMsg.content);
            Console.WriteLine("短信提交结束" + i);
            Console.WriteLine("end empp.SequenceID:" + empp.SequenceID);
            Thread.Sleep(1000);
        }

        private void Connect()
        {
            EMPPLib.ConnectResultEnum result = ConnectResultEnum.CONNECT_OTHER_ERROR;
            try
            {
                LogUtil.toLog("INDE 首次建立连接开始。。");
                result = this.empp.connect(host, port, accountId, password);
            }
            catch (Exception ex)
            {
                LogUtil.toLog("INDE 首次建立连接开始，以失败告终。");
                LogUtil.toLog(ex.ToString());
            }

            int con = 0;
            while (result != EMPPLib.ConnectResultEnum.CONNECT_OK && result != EMPPLib.ConnectResultEnum.CONNECT_KICKLAST)
            {
                LogUtil.toLog("首次连接失败，接下来进行while重连----------" + con);
                con++;
                try
                {
                    result = this.empp.connect(host, port, accountId, password);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }
        }

        private void Reconnect()
        {
            this.empp = new EMPPLib.emptclClass();
            CreatePro(this.empp);

            LogUtil.toLog("发生异常，正在重新连接。。。");
            Console.WriteLine("发生异常，正在重新连接。。。");
            EMPPLib.ConnectResultEnum result = ConnectResultEnum.CONNECT_OTHER_ERROR;
            try
            {
                result = this.empp.connect(host, port, accountId, password);
            }
            catch (Exception ex)
            {
                LogUtil.toLog(ex.ToString());
            }

            while (result != EMPPLib.ConnectResultEnum.CONNECT_OK && result != EMPPLib.ConnectResultEnum.CONNECT_KICKLAST)
            {
                LogUtil.toLog("WHILE   发生异常，进行重新连接。。。");
                Console.WriteLine("WHILE   发生异常，进行重新连接。。。");
                try
                {
                    result = this.empp.connect(host, port, accountId, password);
                    Thread.Sleep(100);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }

            LogUtil.toLog("congratulation , now the connection is ok or kicklast");
            Thread.Sleep(3000);
        }

        private void Disconnect()
        {
            try
            {
                LogUtil.toLog("INDE 断开开始。。。");
                this.empp.disconnect();
            }
            catch (Exception ex)
            {
                LogUtil.toLog("INDE 尝试断开连接，但失败。");
                LogUtil.toLog(ex.ToString());
            }
        }
        #endregion

        public void CreatePro(EMPPLib.emptcl empp)
        {
            Console.WriteLine("进入到createPro函数里面**********************************");
            empp.EMPPClosed += (new _IemptclEvents_EMPPClosedEventHandler(EMPPClosed));
            empp.EMPPConnected += (new _IemptclEvents_EMPPConnectedEventHandler(EMPPConnected));
            empp.MessageReceivedInterface += (new _IemptclEvents_MessageReceivedInterfaceEventHandler(MessageReceivedInterface));
            empp.SocketClosed += (new _IemptclEvents_SocketClosedEventHandler(SocketClosed));
            empp.StatusReceivedInterface += (new _IemptclEvents_StatusReceivedInterfaceEventHandler(StatusReceivedInterface));
            empp.SubmitRespInterface += (new _IemptclEvents_SubmitRespInterfaceEventHandler(SubmitRespInterface));
        }

        public void SubmitRespInterface(SubmitResp sm)
        {
            string str = "收到submitResp:msgId=" + sm.MsgID + ",seqId=" + sm.SequenceID + ",result=" + sm.Result;
            Console.WriteLine("" + sm.ToString());
            Console.WriteLine(str);
            LogUtil.toLog("收到提交返回：" + str);
        }

        public void EMPPClosed(int errorCode)
        {
            LogUtil.toLog("发生了EMPPClose事件");
        }

        public void SocketClosed(int errorCode)
        {
            Console.WriteLine("发生了socketcolse事件");
            string str = "SocketClosed:errorCode=" + errorCode + ",connected=" + empp.connected;
            LogUtil.toLog("发生了socketclose事件：" + "errorcoded is :" + errorCode + "，即将进行重新连接");
            Console.WriteLine(str);
            Reconnect();
        }

        public void MessageReceivedInterface(SMDeliverd sm)
        {
            string str = "收到手机回复:srcId=" + sm.srcID + "               ,content=" + sm.content + "企业扩展位" + sm.DestID;
            string content = sm.content.Trim();
            Console.WriteLine(str);
            LogUtil.toLog(str);
            LogUtil.toLog(content + " - 到此结束");
        }

        public void StatusReceivedInterface(StatusReport sm)
        {
            string str = "收到状态报告:seqId=" + sm.SeqID + ",msgId=" + sm.MsgID + ",mobile=" + sm.DestID + ",destId=" + sm.SrcTerminalId + ",stat=" + sm.Status;
            Console.WriteLine(str);
            LogUtil.toLog(str);
        }

        public void EMPPConnected()
        {
            string str = "已连接";
            Console.WriteLine(str);
        }
    }
}
